package com.su.middle.bp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.jbpm.api.Configuration;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.RepositoryService;
import org.jbpm.api.TaskService;
import org.jbpm.api.task.Task;

import com.su.middle.services.Proposals;

public class ProcessHelper {

	public static ProcessEngine processEngine;

	private static ProcessEngine getProcessEngine() {
		if (processEngine == null) {
			processEngine = new Configuration().setResource("my.jbpm.cfg.xml")
					.buildProcessEngine();
		}
		
		return processEngine;
	}
	
	public static void createProposal(Proposals proposal) {
		if (proposal != null) {
			ProcessEngine prcEngine = getProcessEngine();
			
			RepositoryService repositoryService = prcEngine
					.getRepositoryService();
			ExecutionService executionService = prcEngine.getExecutionService();
			
			repositoryService.createDeployment().addResourceFromClasspath(
					"theses_process.jpdl.xml").deploy();
			HashMap<String, Object> variables = new HashMap<String, Object>();
			variables.put("student_name", proposal.getStudentName());
			variables.put("title", proposal.getThesisTitle());
			variables.put("status", proposal.getStatus());
			variables.put("supervisor_name", proposal.getSupervisorName());
			variables.put("proposal_id", -1);
			
			executionService.startProcessInstanceByKey("ThesesProcess", variables);
		}	
	}
	
	public static Map<String, Proposals> getProposalsForSupervisor(String supervisorName) {
		TreeMap<String, Proposals> result = new TreeMap<String, Proposals>();
		
		if (supervisorName != null) {
			TaskService ts = getProcessEngine().getTaskService();
			List<Task> taskList = ts.findPersonalTasks(supervisorName);
			for (Task task : taskList) {
				String taskId = task.getId();
				Set<String> variableNames = ts.getVariableNames(taskId);
				Map<String, Object> variables = ts.getVariables(taskId, variableNames);
				String sn = (String) variables.get("student_name");
				String title = (String) variables.get("title");
				String status = (String) variables.get("status");
				String supName = (String) variables.get("supervisor_name");
				Proposals p = new Proposals(-1, status, sn, supName, title);
				result.put(taskId, p);
			}
		}
		
		return result;
	}
	
	public static void acceptTask(String taskId) {
		TaskService ts = getProcessEngine().getTaskService();
		ts.completeTask(taskId, "to AcceptProposalTask");		
	}
	
	public static void rejectTask(String taskId) {
		TaskService ts = getProcessEngine().getTaskService();
		ts.completeTask(taskId, "to RejectProposalTask");
	}
}
